﻿#include "ContentBrowserPanel.h"

namespace Hazal
{
	static const std::filesystem::path g_fsAssetPath = "../../Assets";

	CContentBrowserPanel::CContentBrowserPanel()
		: m_currentDirectory(g_fsAssetPath)
	{
		m_textureDirectoryIcon = CTexture2D::Create("../../Assets/Textures/Icons/Directory.png");
		m_textureFileIcon = CTexture2D::Create("../../Assets/Textures/Icons/File.png");
	}

	CContentBrowserPanel::~CContentBrowserPanel()
	{
	}
	
	void CContentBrowserPanel::OnImGuiRender()
	{
		if (ImGui::Begin("Content Browser"))
		{
			if (m_currentDirectory != g_fsAssetPath)
			{
				ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.1f, 0.15f, 1.0f));
				if (ImGui::Button("<-"))
				{
					m_currentDirectory = m_currentDirectory.parent_path();
				}
				ImGui::PopStyleColor();
			}

			static float fPadding = 5.0f;
			static float fThumbnailSize = 90.0f;
			static float fCellSize = fThumbnailSize + fPadding;

			/// Get the real width of current pannel.
			float fPannelWidth = ImGui::GetContentRegionAvail().x;
			int nColumnCount = (int)(fPannelWidth / fCellSize);
			if (nColumnCount < 1)
			{
				nColumnCount = 1;
			}

			/// Arrange icons in different columns
			ImGui::Columns(nColumnCount, 0, false);

			for (auto& dirEntry : std::filesystem::directory_iterator(m_currentDirectory))
			{
				const auto& path = dirEntry.path();
				auto relativePath = std::filesystem::relative(path, g_fsAssetPath);
				std::string strRelativePath = relativePath.filename().string();

				/// Create an image button
				Ref<CTexture2D> textIcon = dirEntry.is_directory() ? m_textureDirectoryIcon : m_textureFileIcon;

				/// Image button about
				{
					ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, { -1.0f, -1.0f });
					ImGui::PushStyleColor(ImGuiCol_Button, { 0, 0, 0, 0 });
					bool bImgBtnClicked = ImGui::ImageButton(strRelativePath.c_str(), (ImTextureID)textIcon->GetRendererID(),
						{ fThumbnailSize, fThumbnailSize }, { 0, 1 }, { 1, 0 });

					/// Button drag
					if (ImGui::BeginDragDropSource())
					{
						const wchar_t* wcItemPath = path.c_str();

						ImGui::SetDragDropPayload("CONTENT_BROWSER_ITEM", wcItemPath, (wcslen(wcItemPath) + 1) * sizeof(wchar_t), ImGuiCond_Once);
						ImGui::EndDragDropSource();
					}

					/// Btn Clicked
					if (bImgBtnClicked)
					{
						if (dirEntry.is_directory())
						{
							m_currentDirectory /= path.filename();
						}
					}
					ImGui::PopStyleColor();
					ImGui::PopStyleVar();
				}

				ImGui::TextWrapped(strRelativePath.c_str());
				ImGui::NextColumn();
			}

			// Reset columns counts.
			ImGui::Columns(1);

			ImGui::End();
		}
	}
}